package com.liuanbang.saro.sarodemo.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.liuanbang.saro.sarodemo.R;
import com.liuanbang.saro.sarodemo.base.BaseActivity;
import com.liuanbang.saro.sarodemo.util.ToastUtils;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by 刘安邦 on 2017/3/10.
 * Email:liuanbang@aliyun.com
 * 描述:下载Demo   2017/3/10
 * 修改:
 * 所需权限:
 * <uses-permission android:name="android.permission.INTERNET" />;
 * <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>;
 * 博客网站:
 * http://blog.csdn.net/u012209506/article/details/56012744#comments
 */
public class DownloadManagerActivity extends BaseActivity {

    @Bind(R.id.fileName)
    TextView fileName;
    @Bind(R.id.updateProgressBar)
    ProgressBar updateProgressBar;
    @Bind(R.id.progressTextView)
    TextView progressTextView;
    @Bind(R.id.down)
    Button down;
    @Bind(R.id.cancel)
    Button cancel;

    private DownloadManager downloadManager = null;
    private String apkUrl = "http://ucdl.25pp.com/fs08/2017/01/20/2/2_87a290b5f041a8b512f0bc51595f839a.apk";

    private TimerTask timerTask = null;
    private Timer timer = null;
    private long id = 0;
    private DownloadManager.Request request = null;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            int pro = bundle.getInt("pro");
            String name = bundle.getString("name");
            updateProgressBar.setProgress(pro);
            progressTextView.setText(String.valueOf(pro) + "%");
            fileName.setText(name);
        }
    };

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_download_manager);
        ButterKnife.bind(this);

        updateProgressBar.setMax(100);


        down.setOnClickListener(this);
        downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        request = new DownloadManager.Request(Uri.parse(apkUrl));

        request.setTitle("大象投教");
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        request.setAllowedOverRoaming(false);
        request.setMimeType("application/vnd.android.package-archive");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        //创建目录
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdir();
        //设置文件存放路径
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "app-release.apk");

        final DownloadManager.Query query = new DownloadManager.Query();
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                Cursor cursor = downloadManager.query(query.setFilterById(id));
                if (cursor != null && cursor.moveToFirst()) {
                    if (cursor.getInt(
                            cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
                        updateProgressBar.setProgress(100);
                        install(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/app-release.apk");
                        timerTask.cancel();
                    }

                    //获取各种
                    String title = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE));
                    String address = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                    int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                    int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                    int pro = (bytes_downloaded * 100) / bytes_total;

                    // Message - Handler 使用
                    Message msg = Message.obtain();
                    Bundle bundle = new Bundle();
                    bundle.putInt("pro", pro);
                    bundle.putString("name", title);
                    msg.setData(bundle);
                    handler.sendMessage(msg);
                }
                cursor.close();
            }

        };

        timer.schedule(timerTask, 0, 1000);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.down:
                getPermission();
                break;
            case R.id.cancel:
                if (!down.isClickable()) {
                    downloadManager.remove(id);
                    ToastUtils.showToast("已取消");
                }
                break;
            default:
                //Do Nothing!
        }
    }

    @Override
    protected void setListener() {
        down.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {

    }

    @Override
    public Toolbar getToolbar() {
        return null;
    }

    /**
     * 获取权限
     */
    private void getPermission() {

        Log.i(TAG, "getPermission:1- " + (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED));
        Log.i(TAG, "getPermission:2- " + (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)));
        //7.0系统报错解决方法 http://blog.csdn.net/czhpxl007/article/details/53781464
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            //已获取外部存储权限
            timerTask.run();
            id = downloadManager.enqueue(request);
            down.setClickable(false);

        } else {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                // 方法用于判断是否该给用户一个解释为何需要打开此权限。如果已经请求过此权限并且用户拒绝，将返回true。
                // 显示给用户的解释
                Log.i(TAG, "getPermission: 给用户解释");
                final AlertDialog.Builder normalDialog = new AlertDialog.Builder(this);
                normalDialog.setTitle("给我权限");
                normalDialog.setMessage("给我存储权限行不行吧,痛快话");
                normalDialog.setPositiveButton("设置",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                getAppDetailSettingIntent(DownloadManagerActivity.this);
                                //...To-do
                            }
                        });
                normalDialog.setNegativeButton("关闭",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //...To-do
                            }
                        });
                // 显示
                normalDialog.show();
            } else {
                // No explanation needed, we can request the permission.
                Log.i(TAG, "getPermission: 申请权限");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
            }
        }

        ActivityCompat.OnRequestPermissionsResultCallback callback = new ActivityCompat.OnRequestPermissionsResultCallback() {
            @Override
            public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
                switch (requestCode) {
                    case 1000: {
                        // If request is cancelled, the result arrays are empty.
                        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                            // 权限请求成功的操作
                            Log.i(TAG, "onRequestPermissionsResult: 申请权限成功");
                            timerTask.run();
                            id = downloadManager.enqueue(request);
                            down.setClickable(false);
                        } else {
                            // 权限请求失败的操作
                            Log.i(TAG, "onRequestPermissionsResult: 申请权限失败");
                            getPermission();
                        }
                        return;
                    }

                    // case其他权限结果。。
                }
            }
        };
    }

    //安装App
    private void install(String path) {
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(this, "com.liuanbang.saro.sarodemo.provider", new File(path));
        } else {
            uri = Uri.parse("file://" + path);
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//4.0以上系统弹出安装成功打开界面
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(intent);
    }

    /**
     * 跳转到应用授权
     */
    private void getAppDetailSettingIntent(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        startActivity(localIntent);
    }
}
